package com.blog.controller.common;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.blog.pojo.MLogin;
import com.blog.util.CookieUtil;
import com.blog.util.JsonUtil;
import com.blog.util.RedisPoolUtil;



/*	
 		该过滤器的作用是: 当用户登录功成功后,每一次操作都会重置用户session时间.
  	
 */
public class SessionExpireFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
		//初始化参数，在创建Filter时自动调用。
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
			
		//拦截到要执行的请求时，doFilter就会执行。这里面写我们对请求和响应的预处理。
		
		 
		//先将ServletRequest(这是个接口) 强转为 HttpServletRequest
		HttpServletRequest httpServletRequest = (HttpServletRequest)request;
		
		String loginToken = CookieUtil.readLoginToken(httpServletRequest);
		
		System.out.println("过滤器拦截到了~");
		if(StringUtils.isNotEmpty(loginToken)){
			
			//判断loginToken是否为空或者""
			//若不为空,符合条件,继续拿user信息
			
			String userStr = RedisPoolUtil.get(loginToken);
			MLogin user = JsonUtil.string2Obj(userStr, MLogin.class);
			if(user != null){
				//若果user不为空,重置用户session时间,即调用expire命令
				//演示，设置为30s
				RedisPoolUtil.expire(loginToken, 30 * 60 );
			}
		}
		
		chain.doFilter(request, response); 
	}

	@Override
	public void destroy() {
		//在销毁Filter时自动调用。
		
	}

}
